﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ToolUtil
{
    public class ProgressHolder : IDisposable
    {
        private FrmPrs _PrgressForm = null;
        BackgroundWorker worker = null;

        public ProgressHolder(DoWorkEventHandler doWork)
        {
            _PrgressForm = new FrmPrs(this, "Processing In Progress");
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged += this.ProgressChanged;
            worker.RunWorkerCompleted += this.ProgressComplete;
            worker.DoWork += doWork;
        }

        public ProgressHolder(DoWorkEventHandler doWork, string title)
        {
            _PrgressForm = new FrmPrs(this, title);
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged += this.ProgressChanged;
            worker.RunWorkerCompleted += this.ProgressComplete;
            worker.DoWork += doWork;
        }

        public void DoIt()
        {
            if (worker == null && worker.IsBusy) return;

            worker.RunWorkerAsync();

            _PrgressForm.ShowDialog();
        }
        public void DoIt(object o)
        {
            if (worker == null && worker.IsBusy) return;

            worker.RunWorkerAsync(o);

            _PrgressForm.ShowDialog();
        }

        public void Abort()
        {
            worker.CancelAsync();
        }

        private void ProgressComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            if (this._PrgressForm != null)
            {
                _PrgressForm.SetStatus("");
                _PrgressForm.SetProgress(0);
                this._PrgressForm.Dispose();
            }
        }
        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string message = e.UserState as string;

            if (message.StartsWith("ERROR:"))
            {
                _PrgressForm.RaiseError(message.Substring(6));
            }
            else if (message.StartsWith("INFORM:"))
            {
                _PrgressForm.RaiseInform(message.Substring(7));
            }
            else
            {
                _PrgressForm.SetStatus(message);
                _PrgressForm.SetProgress(e.ProgressPercentage);
            }
        }

        public void Dispose()
        {
            _PrgressForm.Dispose();
            _PrgressForm = null;

            worker = null;
        }
    }
}
